#include "MissingViewChange.hpp"

using namespace BFT::order::messages;

MissingViewChange::MissingViewChange(uint32_t _view, uint32_t _replicaId, uint32_t _sendingReplica)
	: BFT::messages::MacMessage(MISSING_VIEW_CHANGE, VIEW_NUMBER_SIZE + SENDER_SIZE, _sendingReplica )
{
	viewNo = _view;
	missingReplicaId = _replicaId;
	
	int offset = getOffset();
	int bytes_size;
	boost::shared_ptr<char> bytes = getBytes(bytes_size);
	
	//write down the view number
	*(uint32_t*)(bytes.get()+offset) = htonl(viewNo);
	offset += VIEW_NUMBER_SIZE;
	
	//write down the missing replica ID
	*(uint32_t*)(bytes.get()+offset) = htonl(missingReplicaId);
	offset += SENDER_SIZE;	
}

MissingViewChange::MissingViewChange(boost::shared_ptr<char> _bytes, int _bytes_size)
	: BFT::messages::MacMessage(_bytes, _bytes_size)
{

	if(getTag() != MISSING_VIEW_CHANGE)
	{
		fprintf(stderr,"trying to build a missing view change from bytes with wrong tag\n");
		exit(174);
	}

	int offset = getOffset();
	
	//read the view number
	viewNo = ntohl( *(uint32_t*)(_bytes.get()+ offset) );
	offset += VIEW_NUMBER_SIZE;
	
	//read the missing replica ID
	missingReplicaId = ntohl( *(uint32_t*)(_bytes.get()+ offset) );
	offset += SENDER_SIZE;
	
	if(offset != (int)(_bytes_size - getAuthenticationSize()))
	{
		fprintf(stderr,"trying to build a missing view change from invalid bytes\n");
		exit(175);
	}
	
}
